<?php

/**
 * 获取或创建当前用户ID
 */
function getCurrentUserId() {
    // 如果会话中已有用户ID，直接返回
    if (isset($_SESSION['user_id'])) {
        return $_SESSION['user_id'];
    }
    
    $pdo = getDB();
    $inviteCode = $_GET['code'] ?? '';
    
    if (empty($inviteCode)) {
        // 如果没有邀请码，使用会话ID作为标识
        $sessionId = session_id();
        $stmt = $pdo->prepare("SELECT id FROM users WHERE session_id = ? AND is_invited = 0");
        $stmt->execute([$sessionId]);
        $user = $stmt->fetch();
        
        if ($user) {
            $_SESSION['user_id'] = $user['id'];
            return $user['id'];
        }
        
        // 创建新的未邀请用户
        $stmt = $pdo->prepare("INSERT INTO users (session_id, ip_address, user_agent, is_invited) VALUES (?, ?, ?, 0)");
        $stmt->execute([$sessionId, getClientIP(), $_SERVER['HTTP_USER_AGENT'] ?? '']);
        $newUserId = $pdo->lastInsertId();
        $_SESSION['user_id'] = $newUserId;
        return $newUserId;
    }

    // 查找邀请码对应的用户
    $stmt = $pdo->prepare("SELECT id FROM users WHERE invite_code = ?");
    $stmt->execute([$inviteCode]);
    $user = $stmt->fetch();

    if ($user) {
        $_SESSION['user_id'] = $user['id'];
        return $user['id'];
    }

    // 创建新的邀请用户
    $stmt = $pdo->prepare("INSERT INTO users (session_id, ip_address, user_agent, invite_code, is_invited) VALUES (?, ?, ?, ?, 1)");
    $stmt->execute([session_id(), getClientIP(), $_SERVER['HTTP_USER_AGENT'] ?? '', $inviteCode]);
    $newUserId = $pdo->lastInsertId();
    $_SESSION['user_id'] = $newUserId;
    return $newUserId;
}

/**
 * 获取客户端真实IP
 */
function getClientIP() {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'];
    if (strpos($ip, ',') !== false) {
        $ips = explode(',', $ip);
        $ip = trim($ips[0]);
    }
    return $ip;
}

/**
 * 检查速率限制
 */
function checkRateLimit() {
    $userId = getCurrentUserId();
    $pdo = getDB();

    $stmt = $pdo->prepare("SELECT COUNT(*) FROM anti_cheat_logs WHERE user_id = ? AND last_attempt_time > DATE_SUB(NOW(), INTERVAL ? SECOND)");
    $stmt->execute([$userId, RATE_LIMIT_WINDOW]);
    $count = $stmt->fetchColumn();

    if ($count >= MAX_REQUESTS_PER_WINDOW) {
        return false;
    }

    $stmt = $pdo->prepare("INSERT INTO anti_cheat_logs (user_id) VALUES (?)");
    $stmt->execute([$userId]);

    return true;
}

/**
 * 检查每日抽奖次数限制
 */
function checkDailyLimit() {
    $userId = getCurrentUserId();
    $pdo = getDB();

    // 获取用户信息
    $stmt = $pdo->prepare("SELECT is_invited, invite_code FROM users WHERE id = ?");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    // 统计今日抽奖次数（不包括"谢谢参与"）
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count, GROUP_CONCAT(id) as record_ids 
        FROM winning_records 
        WHERE user_id = ? 
        AND DATE(created_at) = CURDATE()
    ");
    $stmt->execute([$userId]);
    $result = $stmt->fetch();
    $count = $result['count'];

    // 记录详细的调试信息
    error_log(sprintf(
        "抽奖次数检查 - 用户ID: %d, 邀请状态: %d, 邀请码: %s, 今日总抽奖次数: %d, 限制: %d, 记录ID: %s",
        $userId,
        $user['is_invited'],
        $user['invite_code'] ?? 'none',
        $count,
        MAX_ATTEMPTS_PER_DAY,
        $result['record_ids'] ?? 'none'
    ));

    return $count < MAX_ATTEMPTS_PER_DAY;
}

/**
 * 确保默认用户存在
 */
function ensureDefaultUserExists() {
    $pdo = getDB();
    
    // 检查默认用户是否存在
    $stmt = $pdo->prepare("SELECT id FROM users WHERE id = ?");
    $stmt->execute([DEFAULT_USER_ID]);
    
    if (!$stmt->fetch()) {
        // 创建默认用户
        $stmt = $pdo->prepare("INSERT INTO users (id, ip_address, user_agent, is_invited) VALUES (?, '0.0.0.0', 'Default User', 0)");
        $stmt->execute([DEFAULT_USER_ID]);
    }
} 